package edu.ynu.se.xiecheng.achitectureclass.project.service;

import edu.ynu.se.xiecheng.achitectureclass.project.dao.SoilTokenDAO;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Optional;

@Service
public class SoilTokenService {

    private static final Logger log = LoggerFactory.getLogger(SoilTokenService.class);

    @Autowired
    private SoilTokenDAO soilTokenDAO;

    @Autowired
    private RestTemplate restTemplate;

    // 获取土壤检测设备 token 的 URL
    private static final String SOIL_TOKEN_URL = "https://fbox360.com/idserver/core/connect/token";

    // 土壤检测设备的 client_id 和 client_secret
    private static final String CLIENT_ID = "68db2e8bda8d47b5b5db7eaf71c7dcdd"; // 更新为你的 clientId
    private static final String CLIENT_SECRET = "76dc724c95004acab25482d344dab407"; // 更新为你的 clientSecret

    /**
     * 获取或刷新土壤检测设备的访问 token
     *
     * @return 有效的 token
     */
    public String getOrRefreshSoilToken() {
        Optional<Token> optionalToken = soilTokenDAO.findByTypeAndIsDeleted("soil", 0);
        if (optionalToken.isPresent()) {
            Token token = optionalToken.get();
            // 假设 token 没有过期时间字段，直接返回
            return token.getToken();
        }

        // 如果 token 不存在或已过期，则重新获取 token
        return refreshSoilToken();
    }

    /**
     * 刷新并保存土壤检测设备的 token
     *
     * @return 保存的 Token 实体
     */
    public Token refreshAndSaveSoilToken() {
        // 调用土壤检测设备接口获取 token
        String newTokenValue = refreshSoilToken();

        // 保存 token 到数据库
        Token token = new Token();
        token.setToken(newTokenValue);
        token.setType("soil"); // 标记为土壤检测设备的 token
        token.setIsDeleted(0); // 标记为未删除
        return soilTokenDAO.save(token);
    }

    /**
     * 刷新土壤检测设备的访问 token
     *
     * @return 新的 token
     */
    private String refreshSoilToken() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 使用 MultiValueMap 代替 HashMap
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("scope", "fbox");
        requestBody.add("client_id", CLIENT_ID);
        requestBody.add("client_secret", CLIENT_SECRET);
        requestBody.add("grant_type", "client_credentials");

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

        log.info("Sending request to refresh soil token: URL={}, Headers={}, Body={}", SOIL_TOKEN_URL, headers, requestBody);

        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(SOIL_TOKEN_URL, requestEntity, Map.class);

            log.info("Received response: Status={}, Body={}", response.getStatusCode(), response.getBody());

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                return (String) response.getBody().get("access_token");
            } else {
                String errorMessage = "Failed to refresh soil token: " + response.getStatusCode() + " - " + response.getBody();
                throw new RuntimeException(errorMessage);
            }
        } catch (Exception e) {
            log.error("Failed to refresh soil token", e);
            throw new RuntimeException("Failed to refresh soil token: " + e.getMessage(), e);
        }
    }
}